package com.safframework.server.core

import com.safframework.server.core.converter.Converter
import com.safframework.server.core.enums.ServerType
import com.safframework.server.core.log.LogProxy

class ServerBuilder private constructor() {
    var port: Int = 8080
    var address: String = "0.0.0.0"
    var useTls: Boolean = false
    var maxContentLength: Int = 524228

    /**
     * 服务器类型
     */
    var serverType = ServerType.TCP
    var errorController: RequestHandler? = null
    var logProxy: LogProxy? = null
    var converter: Converter? = null

    constructor(init: ServerBuilder.() -> Unit) : this() {
        init()
    }

    // 设置端口号
    fun port(init: ServerBuilder.() -> Int) = apply { port = init() }

    // 设置地址
    fun address(init: ServerBuilder.() -> String) = apply { address = init() }

    // 是否支持 https
    fun useTls(init: ServerBuilder.() -> Boolean) = apply { useTls = init() }

    fun maxContentLength(init: ServerBuilder.() -> Int) = apply { maxContentLength = init() }

    // 设置 http 服务失败的自定义控制器
    fun errorController(init: ServerBuilder.() -> RequestHandler) =
        apply { errorController = init() }

    // 设置日志的实现类，便于开发者使用自己的日志框架
    fun logProxy(init: ServerBuilder.() -> LogProxy) = apply { logProxy = init() }

    fun converter(init: ServerBuilder.() -> Converter) = apply { converter = init() }

    fun serverType(init: ServerBuilder.() -> ServerType) = apply { serverType = init() }

    fun build(): Server {
        return if (ServerType.TCP == serverType) TcpServer(this) else UdpServer(this)
    }
}
